package com.example.myapplication01.service.tinno.ipc.messenger;

import android.app.Service;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.IBinder;
import android.os.Message;
import android.os.Messenger;
import android.os.RemoteException;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

public class MessengerService extends Service {

    private Messenger messenger = new Messenger(new MyHandler());

    class MyHandler extends Handler {
        @Override
        public void handleMessage(@NonNull Message msg) {
            switch (msg.what) {
                case 1:
                    Log.d("MessengerService", "handleMessage: message");
                    Messenger reply = msg.replyTo;
                    Message replyMsg = Message.obtain(null, 1, 0, 0);
                    Bundle bundle = new Bundle();
                    bundle.putString("key", "value");
                    replyMsg.setData(bundle);
                    try {
                        reply.send(replyMsg);
                    } catch (RemoteException e) {
                        throw new RuntimeException(e);
                    }
                    break;
                default:
                    super.handleMessage(msg);
            }
        }
    }

    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return messenger.getBinder();
    }
}